const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const helper = require('../../util/helper');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async (ctx) => {
    let room_id = ctx.params.room_id || 0;
    let product_id = ctx.request.body.product_id || 0;
    // let name = ctx.request.body.name || '';
    try {
        if (parseInt(room_id) <= 0 || parseInt(product_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        let existRows = await mysql.query(`SELECT * FROM room WHERE room_id = ?`, room_id);
        if (existRows.length <= 0) {
            ctx.body = {
                result: 202,
                message: "找不到对应房间"
            };
            return
        }
        existRows = await mysql.query(`SELECT * FROM product WHERE product_id = ?`, product_id);
        if (existRows.length <= 0) {
            ctx.body = {
                result: 202,
                message: "找不到对应设备"
            };
            return
        }
        // existProperties = await mysql.query(`SELECT * FROM product_property WHERE product_id = ?`, product_id);
        // if (existProperties.length <= 0) {
        //     ctx.body = {
        //         result: 203,
        //         message: "找不到对应设备属性"
        //     };
        //     return
        // }
        let tag = "";

        let newRoomDevcieTemp = {
            room_id,
            product_id,
            tag
        };
        let ret = await mysql.query(`INSERT INTO t_room_v_device SET ?`, newRoomDevcieTemp);
        if (!ret || ret.insertId === -1) {
            ctx.body = {
                result: 204,
                message: "新增房间设备模板失败"
            };
        } else {
            ctx.body = {
                result: 200,
                id: ret.insertId,
                message: "新增房间设备模板成功"
            };
        }
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.delete = async (ctx) => {
    let v_device_id = ctx.params.device_id || 0;

    try {
        if (parseInt(v_device_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        ret = await mysql.query(`delete from t_room_v_device WHERE v_device_id = ?`, v_device_id);
        if (!ret || ret.affectedRows === 0) {
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        } else {
            ctx.body = {
                result: 200,
                message: "删除成功"
            };
        }
    } catch (e) {
        ctx.body = {
            result: 203,
            message: "删除失败" + e.toString()
        };
    }
}

exports.update = async (ctx) => {
    let v_device_id = ctx.request.body.device_id || 0;
    let tag = (ctx.request.body.tag ? ctx.request.body.tag.trim() : '') || '';
    let room_id = ctx.params.room_id || 0;

    try {
        if (parseInt(v_device_id) <= 0 || parseInt(room_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        let selectRows = await mysql.query(`SELECT * FROM t_room_v_device WHERE v_device_id = ?`, v_device_id);
        if (selectRows.length > 0) {
            if (tag !== '' && !helper.isJsonArrayString(tag.replace(/\'/g, '\"'))) {
                ctx.body = {
                    result: 202,
                    message: "更新失败,tag格式不对"
                };
                return;
            }
            if (tag !== '') {
                let json_new_tag = JSON.parse(tag.replace(/\'/g, '\"'));
                let property_name_vector = {};
                let sqlQueryCount = `SELECT COUNT(property_id) AS Total from product_property WHERE product_id = ? and property_name in ( `;
                for (let link of Object.values(json_new_tag)) {
                    if (!link.property_name || property_name_vector[link.property_name]) {
                        ctx.body = {
                            result: 203,
                            message: "更新失败,propery_name不存在或重复"
                        };
                        return;
                    }
                    property_name_vector[link.property_name] = link.value;
                    sqlQueryCount += ` '${link.property_name}',`;
                }
                sqlQueryCount = sqlQueryCount.substr(0, sqlQueryCount.length - 1);
                sqlQueryCount += `) `;
                if (json_new_tag.length !== 0) {
                    let selectMatchProperties = await mysql.query(sqlQueryCount, [selectRows[0].product_id, v_device_id]);
                    if (selectMatchProperties[0].Total !== json_new_tag.length) {
                        ctx.body = {
                            result: 204,
                            message: "更新失败,有property_name不存在"
                        };
                        return;
                    }
                }
            }
            selectRows[0].tag = tag;
            ret = await mysql.query(`UPDATE t_room_v_device SET ? WHERE v_device_id = ?`, [selectRows[0], v_device_id]);
            if (!ret || ret.insertId === -1) {
                ctx.body = {
                    result: 202,
                    message: "更新失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新成功"
                };
            }
        } else {
            ctx.body = {
                result: 206,
                message: "对象不存在或者已删除"
            };
        }
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.getList = async (ctx) => {
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let room_id = ctx.query.room_id || 0;
    let ids = [];
    if (!room_id) {
        ctx.body = {
            result: 201,
            message: "无效的房间id"
        };
        return;
    } else {
        ids = JSON.parse(room_id);
    }
    try {
        let IDs = '(';
        for (i = 0; i < ids.length; i++) {
            IDs += (i !== ids.length - 1) ? (ids[i] + ',') : (ids[i] + ')');
        }
        let results = (ids.length > 0) ? await mysql.query(`SELECT * FROM v_temp_device_detail WHERE room_id IN ${IDs} ORDER BY v_device_id DESC LIMIT ${indexfrom}, ${counts} `) : [];
        let totalResult = await mysql.query(`SELECT COUNT(v_device_id) AS total FROM v_temp_device_detail WHERE room_id IN ${IDs} `);
        ctx.body = {
            result: 200,
            list: results,
            totalpage: Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0) / counts),
            totalcounts: totalResult.length > 0 ? totalResult[0].total : 0,
            message: "查询成功"
        };
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}